<template>
  <div class="mewrap">
    <header>
      <van-cell is-link @click="show = true" class="top">
        <template #title>
          <div class="me" v-if="store.istoken">
            <div class="img">
              <img :src="avatar" alt="头像" width="50">
            </div>
            <div class="phone">
              <span>{{ myname }}</span>
            </div>
          </div>
          <div style="font-size: 20px; font-weight: 700;" v-else>
            立即登录
          </div>
        </template>
      </van-cell>
      <van-cell is-link @click="toOrder">
        <template #title>
          <div>
            <i class="iconfont icon-dingdan"></i>
            <span style="margin-left: 5px;">我的订单</span>
          </div>
        </template>
      </van-cell>
      <van-cell title="收货地址" is-link icon="location-o" @click="toAddress" />
    </header>
    <van-action-sheet :round="store.istoken ? true : false" :position="store.istoken ? 'bottom' : 'top'"
      v-model:show="show" :title="!store.istoken ? active == 0 ? '登录' : '注册' : '退出登录'" @close="close" teleport="body">
      <div v-if="!store.istoken">
        <van-tabs v-model:active="active">
          <van-tab :title="item.title" v-for="item in tabList" :key="item.id" />
        </van-tabs>
        <van-form @submit="onSubmit" v-if="active == 0">
          <van-cell-group inset>
            <van-field v-model="name" name="name" label="用户名" placeholder="用户名"
              :rules="[{ required: true, message: '请填写用户名' }]" />
            <van-field v-model="pwd" type="password" name="pwd" label="密码" placeholder="密码"
              :rules="[{ required: true, message: '请填写密码' }]" />
          </van-cell-group>
          <div style="margin: 16px;">
            <van-button round block type="primary" native-type="submit">
              登录
            </van-button>
          </div>
        </van-form>
        <van-form @submit="onSubmit" v-else>
          <van-cell-group inset>
            <van-field v-model="username" name="username" label="用户名" placeholder="用户名"
              :rules="[{ required: true, message: '用户名长度为6-12位,必须以字母开头并且只能输入大小写和数字', pattern: /^[a-z][a-z0-9]{5,11}$/i }]" />
            <van-field v-model="password" type="password" name="password" label="密码" placeholder="密码"
              :rules="[{ required: true, message: '密码长度为6-12位,并且只能输入大小写和数字', pattern: /^[a-z0-9]{6,12}$/i }]" />
            <van-field v-model="confirm" type="password" name="confirm" label="确认密码" placeholder="请再次输入密码"
              :rules="[{ required: true, message: '两次输入的密码不一致', pattern: new RegExp(password) }]" />
          </van-cell-group>
          <div style="margin: 16px;">
            <van-button round block type="primary" native-type="submit">
              立即注册
            </van-button>
          </div>
        </van-form>
      </div>
      <div v-else style="padding: 30px 15px 50px;">
        <van-button round block type="primary" @click="logOut">
          退出登录
        </van-button>
      </div>
    </van-action-sheet>
</div>
</template>
<script setup>
import { useRouter, useRoute } from 'vue-router';
import { ref, onMounted } from 'vue';
import avatar from "@assets/images/avatar.webp"
import { toPage, isWeiXin, redirectTo } from '@/utlis/tools';
import { login, register, getUserInfo } from "@/api/index"
import { showSuccessToast } from "vant";
import { useStore } from "@/store"
const store = useStore();

const router = useRouter()
const route = useRoute()
const show = ref(false)
const active = ref(0);
const tabList = ref([
  { id: 1, title: "登录" },
  { id: 2, title: "注册" },
])
const name = ref('');
const pwd = ref('');
const username = ref('');
const password = ref('');
const confirm = ref('');
const myname = ref('')

onMounted(() => {
  if (route.query?.istoken == "1") {
    store.tabkey = 3
    sessionStorage.setItem("tabKey", 3)
    show.value = true
    store.istoken = false
  }
  let token = localStorage.getItem("token")
  if (token) {
    store.istoken = true
    getInfo()
  } else {
    store.istoken = false
  }
})
const close = () => {
  name.value = ''
  pwd.value = ''
  username.value = ''
  password.value = ''
  confirm.value = ''
}
const onSubmit = async (val) => {
  console.log('submit', val);
  if (active.value == 0) {
    const { data, code } = await login({
      username: val.name,
      userpwd: val.pwd
    })
    if (code == 200) {
      showSuccessToast("登录成功")
      store.tabkey = 3
      show.value = false
      setTimeout(() => {
        localStorage.setItem("token", data)
        getInfo()
        store.istoken = true
        close()
      }, 400)
    }
  } else {
    const { code } = await register({
      username: val.username,
      userpwd: val.password
    })
    if (code == 200) {
      showSuccessToast("注册成功")
      active.value = 0
      close()
    }
  }
};
const logOut = () => {
  show.value = false
  setTimeout(() => {
    localStorage.removeItem("token")
    showSuccessToast("退出登录")
    store.istoken = false
    myname.value = ''
  }, 300)
}
const toOrder = () => {
  if (!store.istoken) {
    show.value = true
    return
  }
  router.push('myorder')
}
const toAddress = () => {
  if (!store.istoken) {
    show.value = true
    return
  }
  router.push('address')
}
const getInfo = async () => {
  const { data, code } = await getUserInfo({ type: "self" })
  if (code == 200) {
    myname.value = data.username
  }
}

</script>
<style lang="less" scoped>
.mewrap {

  header {
    .top {
      /deep/.van-cell__right-icon {
        align-self: center;
      }
    }

    .me {
      display: flex;
      align-items: center;
    }

    .img {
      img {
        border-radius: 30px;
      }
    }

    .phone {
      margin-left: 30px;
      font-size: 24px;
      font-weight: 700;
    }
  }
}
</style>
